from rest_framework import serializers

from goods.models import SKU


class CartSerializer(serializers.Serializer):
    #购物车数据序列化器
    sku_id = serializers.IntegerField(label='sku id ', min_value=1)
    count = serializers.IntegerField(label='数量', min_value=1)
    selected = serializers.BooleanField(label='是否勾选', default=True)

    def validate(self, data):
        try:
            sku=SKU.objects.get(id=data['sku_id'])
        except SKU.DoesNotExist:
            raise serializers.ValidationError('商品不存在')

        if data['count']>sku.stock:
            raise serializers.ValidationError('商品库存不足')
        return  data

#购物车商品的序列化器
class CartSKUSerializer(serializers.ModelSerializer):
    #商品数据序列化器
    count = serializers.IntegerField(label='数量')
    selected = serializers.BooleanField(label='是否勾选')

    class Meta:
        model=SKU
        fields = ('id', 'count', 'name', 'default_image_url', 'price', 'selected')

#删除购物车数据序列化器
class CartDeleteSerializer(serializers.Serializer):
    #只返回sku_id 字段中没有要重新设置一个字段
    sku_id = serializers.IntegerField(label='商品id', min_value=1)
    #校验ｓｋｕ＿ｉｄ的值
    def validated_sku_id(self,value):
        try:
            sku=SKU.objects.get(id=value)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('商品不存在')
        return value

#购物车全选序列化器
class CartSelectAllSerializer(serializers.Serializer):
    #请求selected  只返回一个字段message
    selected = serializers.BooleanField(label='全选')




